package org.alvin.bolai;

import io.netty.buffer.ByteBufUtil;
import org.alvin.bolai.bkv.BKV;
import org.alvin.bolai.bkv.UnpackBKVResult;

import java.io.IOException;

public class BolaiBkcTest {

//

    public static void main(String[] args) {
        String cmd = "fcff004a0a01020000000000000051080103474032901081040101100703010800030112050301130104011401e003012c0314012d00c80064001e01f400c8001e04b0012c001e03014701c9fcfe";
        byte[] buff = ByteUtils.hexToByteArray(cmd);
        int sizes = buff.length;
        if (sizes <= 4) {
            return;
        }
        int index = 0;
        int start1 = buff[0];
        index++;
        int start2 = buff[1];
        index++;
        //上行帧头
        if (start1 != (byte) 0xFC || !(start2 == (byte) 0xFF || start2 == (byte) 0xFE)) {
            return;
        }
        //获取长度
        int length = ByteUtils.bytes2ToIntHL(new byte[]{buff[2], buff[3]});
        if (length > buff.length) {
            return;
        }
        index += 2;
        //消息体 去掉校验位和帧长，获取数据
        byte[] data = new byte[length - 3];
        System.arraycopy(buff, 4, data, 0, data.length);
        //校验和
        index += data.length;
        System.out.println(index);
        byte [] checkBuff = new byte[]{buff[index]};
        int checkSum = Integer.valueOf(ByteBufUtil.hexDump(new byte[]{buff[index]}), 16);
        index++;
        //校验和
        byte[] checkSumBuff = new byte[length - 1];
        System.arraycopy(buff, 2, checkSumBuff, 0, checkSumBuff.length);
        //尾帧
        byte[] end = new byte[2];
        System.arraycopy(buff, index, end, 0, end.length);
        index += 2;
        //判断尾帧 ，判断校验和
        // 尾帧暂时忽略
        // 判断校验和
        System.out.println("信息头："+ ByteUtils.byte2Hex(new byte[]{buff[0], buff[1]}));
        System.out.println("帧长:" +length);
        UnpackBKVResult unpackBKVResult = BKV.unpack(data);
        BKV bkv = unpackBKVResult.getBKV();
        bkv.dump();
        System.out.println("校验：" + ByteUtils.byte2Hex(checkBuff));
        System.out.println("帧尾：" + ByteUtils.byte2Hex(end));

}
}
